#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/wait.h>

#define PORT 8080
#define BUFFER_SIZE 1024

void handle_client(int client_socket) {
    char request[BUFFER_SIZE];
    char response[BUFFER_SIZE];
    int n;

    // 读取客户端请求
    n = read(client_socket, request, BUFFER_SIZE);
    if (n > 0) {
        request[n] = '\0'; // 确保字符串以null结尾
        printf("Client request: %s\n", request);

        // 简单的HTTP响应
        strcpy(response, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
        strcat(response, "<html><body><h1>Hello, World!</h1></body></html>");
        write(client_socket, response, strlen(response));
    }

    // 关闭客户端套接字
    close(client_socket);
    exit(0); // 子进程退出
}

int main() {
    int server_socket, client_socket;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);

    // 创建套接字
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定套接字
    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("Bind failed");
        close(server_socket);
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_socket, 5) < 0) {
        perror("Listen failed");
        close(server_socket);
        exit(EXIT_FAILURE);
    }

    printf("Server is running on port %d...\n", PORT);

    while (1) {
        // 接受客户端连接
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_len);
        if (client_socket < 0) {
            perror("Accept failed");
            continue;
        }

        // 创建子进程处理客户端请求
        pid_t pid = fork();
        if (pid < 0) {
            perror("Fork failed");
            close(client_socket);
            continue;
        } else if (pid == 0) {
            // 子进程
            close(server_socket); // 子进程不需要监听套接字
            handle_client(client_socket);
        } else {
            // 父进程
            close(client_socket); // 父进程关闭客户端套接字
            waitpid(pid, NULL, WNOHANG); // 防止僵尸进程
        }
    }

    // 关闭服务器套接字
    close(server_socket);
    return 0;
}